<script>
	var server_url = 'https://ymq.appheader.com'//后台地址
	export default {
		globalData:{
			server_url:server_url,//后台地址
			login: server_url + '/api/public/login/xcx',//用户登录接口
			scenario:'',//场景值
			openGetShareCode:'',//打开时的分享码
			userInfo:{},//当前用户的信息
		},
		onLaunch: function(options) {
			var _this=this;
			//获取小程序场景值
			_this.globalData.scenario=options.scene;
			//获取分享码（检测有无）
			if (options.query.share_code) {
			    _this.globalData.openGetShareCode = options.query.share_code;//全局变量
				uni.setStorageSync('share_code', options.query.share_code);//本地缓存
			} else {
			    _this.globalData.openGetShareCode = ''
			}
		},
		methods:{
			//获取用户信息
			userGet: function (isAuth, ok) {
				var _this = this;
				_this.post("/user/user/get", {}, function (res) {
					_this.globalData.userInfo = res.data.data;
					_this.share_code = res.data.data.share_code;
					if (isAuth) {
						if (ok) {
							_this.auth(_this.globalData.userInfo, ok);
						} else {
							_this.auth(_this.globalData.userInfo);
						}
					} else {
						if (ok) {
							ok(res.data.data);
						}
					}
				}, function () {
					uni.showModal({
						title: '加载失败',
						content: '网络加载失败，是否重新加载',
						success(res) {
							if (res.confirm) {
								_this.userGet();
							} else if (res.cancel) {
								console.log('用户点击取消')
							}
						}
					});
				});
			},
			//更改用户信息
			auth: function (userInfo, ok) {
				var _this = this;
				//根据传入的用户信息去刷新全局变量中的用户信息
				for (var i in userInfo) {
					this.globalData.userInfo[i] = userInfo[i];
				}
				uni.request({
					url: _this.globalData.server_url + '/user/user/wxinfo',
					data: {
						userinfo: userInfo,
					},
					header: {
						sessionid: uni.getStorageSync('sessionid'),
						'content-type': 'application/json' // 默认值
					},
					success: function (res) {
						console.log('app.js 调用服务器小程序授权返回结果：', res.data);
						if (ok) {
							ok();
						}
					}
				});
			},
			//登录
			userLogin: function () {
				var _this = this;
				//定义promise方法
				return new Promise(function (resolve, reject) {
					uni.login({
						provider: 'weixin',//登陆服务提供商 此处微信
						scopes:'auth_base',//授权类型，默认 auth_base。支持 auth_base（静默授权）/ auth_user（主动授权） / auth_zhima（芝麻信用）
						success: res => {
							//请求登陆功能成功
							if (res.code) {
								//调用后台的用户登录接口：登录功能获得openid=>后台=>获得sessionid
								uni.request({
									url: _this.globalData.login,
									data: {
										code: res.code,
										share_code: _this.globalData.openGetShareCode,
										scene: _this.globalData.scenario
									},
									header: {
										'content-type': 'application/json'
									},
									success: function (res) {
										if (res.data.errno == '88888') {
											_this.go('warn', "reLaunch");
										} else if (res.data.errno == '0') {
											uni.setStorageSync('sessionid', res.data.data);
											_this.userGet()
											resolve(res.data);
										} else {
											reject('error');
										}
									},
									fail: function (res) {
										reject(res);
										uni.showToast({
											title: '系统错误，登录失败',
											icon:'none'
										});
									}
								});
							} else {
								reject("error");
							}
						}
					});
				}).catch((e) => {});
			},
			//post请求
			post: function (url, data, ok, err) {
			    var _this = this;
			    var port = url;
			    url = server_url + url;
			    var sessionid = uni.getStorageSync('sessionid');
			    if (!data) {
			        data = {};
			    }
				//请求后台时，检测参数中有无share_code,若无,调用全局个人信息的share_code
			    if (!data.share_code) {
			        var share_code = _this.globalData.openGetShareCode;
			        if (share_code) {
			            if (share_code != _this.globalData.userInfo.share_code) {
			                data.share_code = share_code;
			            }
			        }
			    }
			    var options = {
			        url: url,
			        data: data,
			        header: {
			            'content-type': 'application/json', // 默认值
			            'sessionid': sessionid
			        },
			        success: function (res) {
			            console.log(port + '请求成功res:----------', res);
			            if (res.data.errno == 10000) {
			                console.log('----------------会话过期准备重新登录')
			                _this.userLogin().then(res => {
			                    if (res.errno == 0) {
			                        options.header.sessionid = uni.getStorageSync('sessionid');
			                        uni.request(options);
			                    }
			                });
			            } else if (res.data.errno != 0) {
			                if (err) {
			                    err(res);
			                }
			                uni.showToast({
			                    title: res.data.errmsg,
			                    icon: "none"
			                }, 3000);
			            } else if (ok) {
			                ok(res);
			            }
			        },
			        fail: function (res) {
			            console.log('---------post请求失败res:', res);
			            if (err) {
			                err(res);
			            }
			        }
			    }
			    if (!sessionid) {
			        _this.userLogin().then(res => {
			            if (res.errno == 0) {
			                options.header.sessionid = uni.getStorageSync('sessionid');
			                uni.request(options);
			            }
			        });
			    } else {
			        options.header.sessionid = uni.getStorageSync('sessionid');
			        uni.request(options);
			    }
			},
			/**
			 * 页面url跳转
			 * page url参数 当type为navback时page为number类型参数
			 * type跳转的方式
			 * type navigateTo, redirectTo,switchTab,navigateBack,reLaunch
			 */
			go: function (page, type, success, fail, complete) {
			    var page0 = page;
			    if (String(page).indexOf("?") != -1) {
			        page0 = page.split("?")[0];
			    }
			    var obj = {
			        url: "/pages/" + page0 + "/" + page
			    }
			    if (!type) { //type不为空就先跳转过去
			        uni.redirectTo(obj);
			    } else {
			        if (success) {
			            obj.success = function (res) {
			                success(res);
			            };
			        }
			        if (fail) {
			            obj.fail = function (res) {
			                fail(res);
			            };
			        }
			        if (complete) {
			            obj.complete = function (res) {
			                complete(res);
			            };
			        }
			        if (type == "navigateBack") {
			            uni.navigateBack(Number(page));
			        } else if (type == "navigateTo") {
			            uni.navigateTo(obj)
			        } else if (type == "redirectTo") {
			            uni.redirectTo(obj);
			        } else if (type == "switchTab") {
			            uni.switchTab(obj);
			        } else if (type == "reLaunch") {
			            uni.reLaunch(obj);
			        }
			    }
			},
		},	
	}
</script>

<style>
	/*每个页面公共css */
</style>
